package com.lg.baselibrary.utils;

import android.os.Handler;
import android.os.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class FileDownloader {

	private DownloadCallback callback;
	public void download(String fileUrl,String dstFilePath,DownloadCallback callback){
		this.callback = callback;
		new DownloadThread(fileUrl, dstFilePath).start();
	}
	private class DownloadThread extends Thread{
		String fileUrl;
		String dstFilePath;
		public DownloadThread(String fileUrl, String dstFilePath) {
			super();
			this.fileUrl = fileUrl;
			this.dstFilePath = dstFilePath;
		}

		@Override
		public void run() {
			try {
				URL url = new URL(fileUrl);
				URLConnection conn = url.openConnection();
				conn.setReadTimeout(8000);
				conn.setConnectTimeout(8000);
				int contentLength = conn.getContentLength();
				InputStream is = conn.getInputStream();
				File file = new File(dstFilePath);
				if(!file.getParentFile().exists()){
					file.getParentFile().mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buff = new byte[1024*2];
				int len;
				int count = 0;
				while((len = is.read(buff)) != -1){
					fos.write(buff, 0, len);
					count += len;
					handler.sendMessage(handler.obtainMessage(0, contentLength, count));
				}
				fos.close();
				handler.sendMessage(handler.obtainMessage(1, file));
				return;
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			handler.sendEmptyMessage(2);
		}
	}
	private Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if(callback != null){
				switch (msg.what) {
				case 0:
					callback.onLoading(msg.arg1, msg.arg2);
					break;
				case 1:
					callback.onSuccess((File) msg.obj);
					break;
				case 2:
					callback.onFailed();
					break;
				}
			}

			return false;
		}
	});
	public interface DownloadCallback{
		void onSuccess(File file);
		void onFailed();
		void onLoading(long total, long current);
	}
}
